package controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis"
	"github.com/gogf/gf/util/gconv"
	"rock/customer/dto"
	"rock/customer/initParam"
	"rock/customer/middleware"
	"rock/customer/modules/redisModules"
)

// @Summary 获取融云token
// @Description 传参只需要传UserId，Name，PortraitUri。融云token init融云SDK时携带的token
// @Tags 融云
// @ID   /rctoken
// @Accept  json
// @Produce  json
// @Param polygon body dto.RongCloudTokenInput true "body"
// @Success 200 {object} middleware.Response{data=dto.RongCloudTokenOutput} "success"
// @Router /rctoken [post]
func (r *RongCloudController) getRongCloudToken(router *gin.Context) {
	params := &dto.RongCloudTokenInput{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	//
	//getRongCloudToken_127317_1
	redisCache := redisModules.ClientRedis.Get(initParam.RCTokenPrefix + params.UserId + "_" + gconv.String(params.IsCustomerClient))
	val, err := redisCache.Result()
	if err == nil {
		responseData := dto.RongCloudTokenOutput{}
		err = json.Unmarshal([]byte(val), &responseData)
		if err != nil {
			middleware.ResponseError(router, middleware.USER_NOT_EXIST, err)
			return
		}
		middleware.ResponseSuccess(router, responseData)
		return
	} else {
		if err != redis.Nil {
			middleware.ResponseError(router, middleware.USER_NOT_EXIST, err)
			return
		}
	}
	//
	if params.IsCustomerClient == 1 {
		params.UserId = initParam.CTarget + params.UserId
	} else {
		params.UserId = initParam.CsTarget + params.UserId
	}
	rcParam := fmt.Sprintf("userId=%s&name=%s&portraitUri=%s", params.UserId, params.Name, params.PortraitUri)
	fmt.Println(rcParam)
	responseData, err := getRonCloudToken(rcParam)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	//存入缓存
	err = addRedis(router, responseData, initParam.RCTokenPrefix + params.UserId + "_" + gconv.String(params.IsCustomerClient))
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	middleware.ResponseSuccess(router, responseData)
}
